/*
 * Thread.h
 *
 *  Created on: Sep 10, 2011
 *      Author: Gherman Alin
 */

#ifndef THREADS__THREAD_H_
#define THREADS__THREAD_H_

#include "Runnable.h"
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <string>

namespace Threads {

class ThreadUsageException: public std::runtime_error {
public:
	ThreadUsageException() :
			std::runtime_error("ThreadUsageException") {
	}

	ThreadUsageException(const std::string& msg) :
			std::runtime_error(msg) {
	}
};

/**
 * Thread class after the model of the java Thread class
 * must override the run() method that does the work
 */
class Thread: public Runnable {
public:
	Thread();
	Thread(Runnable* target);
	virtual ~Thread();

	/**
	 * Starts a new thread that executes the
	 * run() method
	 */
	void start();

	/**
	 * This method executes in another thread
	 *
	 * If a target is specified the run() method of
	 * the target is called, otherwise this method
	 * doesn't do anything (must be overwritten)
	 */
	void run();

	/**
	 * Waits for the termination of the started thread (if any)
	 *
	 * NOTE: this method is called in the destructor
	 */
	void join();

private:
	boost::thread *thisThread;
	boost::mutex thisMutex;

	Runnable* target;
};

}

#endif
